<script lang="ts" setup>
import type { TableColumns } from '@/types/antd'
import { useRouter } from 'vue-router'

defineOptions({
	name: 'rbac_role_RoleList'
})

const router = useRouter()
const dataSource = ref([])
const pagination = reactive({
	current: 1,
	pageSize: 10,
	total: 0
})
const queryParams = reactive({
	name: '',
	status: ''
})

// 使用函数动态返回表头，实现语言切换时的实时更新
const columns = computed(
	(): TableColumns => [
		{
			title: t('角色列表.角色名'),
			dataIndex: 'name',
			align: 'center' as const,
			key: 'name'
		},
		{
			title: t('角色列表.状态'),
			dataIndex: '_status',
			align: 'center' as const,
			key: '_status'
		},
		{
			title: t('角色列表.创建时间'),
			dataIndex: '_created_at',
			align: 'center' as const,
			key: '_created_at'
		},
		{
			title: t('角色列表.操作'),
			key: 'action',
			dataIndex: 'action',
			align: 'center' as const
		}
	]
)

const fetch = () => {
	const formParams: any = {
		page: pagination.current,
		pageSize: pagination.pageSize,
		name: queryParams.name,
		status: queryParams.status
	}
	formParams.permissionName = '权限管理-角色列表'
	Api.post('/rbac/role/list', formParams, true).then((res: any) => {
		dataSource.value = []
		res.items.forEach((item: any) => {
			dataSource.value.push(item)
		})
		pagination.total = res._meta.totalCount
	})
}

const handleTableChange = (newPagination: any) => {
	pagination.current = newPagination.current
	pagination.pageSize = newPagination.pageSize
	fetch()
}

const addRole = () => {
	router.push('/rbac/role/add')
}

const editRole = (record: any) => {
	router.push({ path: '/rbac/role/edit', query: { id: record.id } })
}

onMounted(() => {
	fetch()
})
</script>

<template>
	<IsGuest>
		<view :class="{ 'rbac-RoleList': true }">
			<view>
				<a-form :model="queryParams" layout="inline">
					<a-form-item :label="t('角色列表.角色名')">
						<a-input
							v-model:value="queryParams.name"
							:placeholder="t('角色列表.请输入角色名')" />
					</a-form-item>
					<a-form-item>
						<a-button type="primary" html-type="submit" @click="fetch">
							{{ t('按钮.筛选') }}
						</a-button>
					</a-form-item>
					<a-form-item>
						<a-button type="default" html-type="submit" @click="addRole">
							{{ t('角色列表.添加角色') }}
						</a-button>
					</a-form-item>
				</a-form>
			</view>
			<a-divider />
			<view>
				<a-table
					:columns="columns"
					:bordered="true"
					:data-source="dataSource"
					:pagination="pagination"
					@change="handleTableChange">
					<template #bodyCell="{ text, record, index, column }">
						<template v-if="column.key === 'action'">
							<a-button @click="editRole(record)">
								{{ t('角色列表.编辑角色') }}
							</a-button>
						</template>
					</template>
				</a-table>
			</view>
		</view>
	</IsGuest>
</template>

<style lang="scss" scoped></style>
